import React, { useState, useEffect } from 'react';
import { Modal, Form, Table, Row, Col, Radio, Divider } from 'antd';
import notificationService from '../../../../../services/notificationService';
import type { FormInstance } from 'antd';
import { getFormInitialValues, resetFormToDefault, saveFormDefaultValues, saveFormInitialValues } from '../../../../../components/utils/formStorage';
import NumberField from '../../../../../components/common/NumberField';
import useIpcCalculation from '../../../hooks/useIpcCalculation';
import CalcControls from '../../../../../components/common/CalcControls';
import { ResultItem } from '../../../../../../shared/types';

// 定义表单数据类型
interface FormValues {
  // 桁架参数
  trussLength_load: number;
  trussHeight_load: number;
  trussWidth_load: number;
  topChordDiameter_load: number;
  bottomChordDiameter_load: number;
  webThickness_load: number;
  webDiameter_load: number;
  topChordThickness_load: number;
  bottomChordThickness_load: number;
  steelDensity_load: number;
  verticalSpacing_load: number;
  safetyFactor_load: number;
  topChordHorizontalDiameter_load: number;
  topChordDiagonalDiameter_load: number;
  topChordHorizontalThickness_load: number;
  topChordDiagonalThickness_load: number;
}

interface InvertedTriangularLoadCalculationProps {
  visible: boolean;
  onCancel: () => void;
  initialValues?: FormValues;
}

// 默认初始值常量
const DEFAULT_VALUES: FormValues = {
  // 桁架参数
  trussLength_load: 14.0,
  trussHeight_load: 1.0,
  trussWidth_load: 0.8,
  topChordDiameter_load: 0.089,
  bottomChordDiameter_load: 0.089,
  webThickness_load: 0.004,
  webDiameter_load: 0.057,
  topChordThickness_load: 0.006,
  bottomChordThickness_load: 0.006,
  steelDensity_load: 7850,
  verticalSpacing_load: 1.4, // 竖杆间隔 (m)
  safetyFactor_load: 1.2,
  topChordHorizontalDiameter_load: 0.076,
  topChordDiagonalDiameter_load: 0.057,
  topChordHorizontalThickness_load: 0.004,
  topChordDiagonalThickness_load: 0.004,
};

const InvertedTriangularLoadCalculation: React.FC<InvertedTriangularLoadCalculationProps> = ({ 
  visible, 
  onCancel,
  initialValues = DEFAULT_VALUES
}) => {

  const [form]: [FormInstance<FormValues>] = Form.useForm<FormValues>();
  const [resultData, setResultData] = useState<ResultItem[]>([]);
  const formKey = 'inverted-triangular-load';

  // 保存初始值到工具函数中
  useEffect(() => {
    saveFormDefaultValues(formKey, initialValues);
  }, []);

  useEffect(() => {
    if (visible) {
      try {
        // 获取保存的上次输入参数，如果没有则使用初始值
        const lastParams = getFormInitialValues(formKey) || initialValues;
        // 使用 setTimeout 确保表单已经挂载后再设置字段值
        setTimeout(() => {
          form.setFieldsValue(lastParams);
          setResultData([]);
        }, 0);
      } catch (error) {
        console.error('表单初始化延迟，这是正常的:', error);
        // 使用 setTimeout 确保表单已经挂载后再设置字段值
        setTimeout(() => {
          form.setFieldsValue(initialValues);
          setResultData([]);
        }, 0);
      }
    }
  }, [visible, initialValues, form]);

  // 使用自定义 Hook 进行 IPC 计算
  const { runCalculation } = useIpcCalculation();

  // 自重荷载计算
  const handleSelfWeightCalculate = async () => {
    try {
      // 验证表单
      const values = await form.validateFields();
      
      // 保存表单值
      saveFormInitialValues(formKey, values);
      
      // 根据竖杆间隔计算面板数
      const panels = Math.round(values.trussLength_load / values.verticalSpacing_load);
      
      // 转换参数名称以匹配后端期望的格式
      const backendParams = {
        length: values.trussLength_load,
        height: values.trussHeight_load,
        width: values.trussWidth_load,
        topChordDiameter: values.topChordDiameter_load,
        bottomChordDiameter: values.bottomChordDiameter_load,
        webDiameter: values.webDiameter_load,
        topChordThickness: values.topChordThickness_load,
        bottomChordThickness: values.bottomChordThickness_load,
        webThickness: values.webThickness_load,
        steelDensity: values.steelDensity_load,
        verticalWebSpacing: values.verticalSpacing_load, // 注意这里的名称转换
        topChordHorizontalDiameter: values.topChordHorizontalDiameter_load,
        topChordDiagonalDiameter: values.topChordDiagonalDiameter_load,
        topChordHorizontalThickness: values.topChordHorizontalThickness_load,
        topChordDiagonalThickness: values.topChordDiagonalThickness_load,
        safetyFactor: values.safetyFactor_load,
        panels
      };
      
      // 调用后端计算服务
      const apiRes = await runCalculation('crossing-inverted-triangular-truss-load-calculation', backendParams, (data: any) => {
        // 由于后端算法没有直接返回某些字段，我们在前端计算这些值
        // 注意：根据算法实现，上弦横杆和斜杆重量已经包含在webWeight中了
        const topChordTotalWeight = data.topChordWeight;
        const totalWeightWithSafety = data.totalWeight * values.safetyFactor_load;
        
        return [
          // 上弦杆
          { key: 'topChordWeight', name: '上弦杆重量', value: data.topChordWeight, unit: 'kg', category: '上弦杆' },
          
          // 下弦杆
          { key: 'bottomChordWeight', name: '下弦杆重量', value: data.bottomChordWeight, unit: 'kg', category: '下弦杆' },
          
          // 腹杆
          { key: 'webWeight', name: '腹杆重量', value: data.webWeight, unit: 'kg', category: '腹杆' },
          
          // 总计
          { key: 'totalWeight', name: '桁架总重量', value: data.totalWeight, unit: 'kg', category: '总计' },
          { key: 'totalWeightWithSafety', name: '考虑安全系数的总重量', value: parseFloat(totalWeightWithSafety.toFixed(2)), unit: 'kg', category: '总计' },
          { key: 'linearLoad', name: '线荷载', value: data.linearLoad, unit: 'N/m', category: '总计' },
        ];
      });
      
      if (!apiRes.success) throw new Error('calculate-failed');
      
      setResultData(apiRes.results as ResultItem[]);
      notificationService.success('计算完成');
      
      return apiRes;
    } catch (error: any) {
      console.error('自重荷载计算过程中发生错误:', error);
      // 处理表单验证错误和其他错误
      if (!error || !error.errorFields) {
        notificationService.error('计算过程中发生错误');
      }
    }
  };

  const handleReset = () => {
    // 重置表单到默认保存的默认值并清空结果
    resetFormToDefault(form, formKey);
    setResultData([]);
    notificationService.success('已重置到默认参数');
  };

  const columns = [
    { title: '项目', dataIndex: 'name', key: 'name' },
    { title: '数值', dataIndex: 'value', key: 'value' },
    { title: '单位', dataIndex: 'unit', key: 'unit' },
  ];

  // 按类别过滤结果数据
  const getFilteredResults = (category: string) => {
    return resultData.filter(item => item.category === category);
  };

  return (
      <Modal
      title="倒三角桁架荷载计算"
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={1200}
    >
      <div style={{ display: 'flex', gap: 20 }}>
        <div style={{ flex: 1 }}>
          <div>
            <Form form={form} layout="vertical">
              <Row gutter={16}>
                <Col span={12}>
                  <NumberField name="trussLength_load" label="桁架长度 (m)" required min={0} step={0.1} />
                  <NumberField name="trussHeight_load" label="桁架高度 (m)" required min={0} step={0.1} />
                  <NumberField name="trussWidth_load" label="桁架宽度 (m)" required min={0} step={0.1} />
                  <NumberField name="topChordDiameter_load" label="上弦杆直径 (m)" required min={0} step={0.001} />
                  <NumberField name="bottomChordDiameter_load" label="下弦杆直径 (m)" required min={0} step={0.001} />
                  <NumberField name="webDiameter_load" label="腹杆直径 (m)" required min={0} step={0.001} />
                  <NumberField name="topChordHorizontalDiameter_load" label="上弦横杆直径 (m)" required min={0} step={0.001} />
                  <NumberField name="topChordDiagonalDiameter_load" label="上弦斜杆直径 (m)" required min={0} step={0.001} />
                </Col>
                <Col span={12}>
                  <NumberField name="steelDensity_load" label="钢材密度 (kg/m³)" required min={0} step={1} />
                  <NumberField name="verticalSpacing_load" label="竖杆间隔 (m)" required min={0.1} step={0.1} />
                  <NumberField name="safetyFactor_load" label="安全系数" required min={1} step={0.1} />
                  <NumberField name="topChordThickness_load" label="上弦杆壁厚 (m)" required min={0} step={0.001} />
                  <NumberField name="bottomChordThickness_load" label="下弦杆壁厚 (m)" required min={0} step={0.001} />
                  <NumberField name="webThickness_load" label="腹杆壁厚 (m)" required min={0} step={0.001} />
                  <NumberField name="topChordHorizontalThickness_load" label="上弦横杆壁厚 (m)" required min={0} step={0.001} />
                  <NumberField name="topChordDiagonalThickness_load" label="上弦斜杆壁厚 (m)" required min={0} step={0.001} />
                </Col>
              </Row>
              
              <Divider />
              
              <Form.Item>
                <CalcControls
                  onCalculate={handleSelfWeightCalculate}
                  onReset={handleReset}
                />
              </Form.Item>
            </Form>
          </div>
        </div>
        
        <div style={{ flex: 1 }}>
          <div>
            <h3>构件重量</h3>
            <Table 
              dataSource={[
                ...getFilteredResults('上弦杆'), 
                ...getFilteredResults('下弦杆'),
                ...getFilteredResults('腹杆')
              ]} 
              columns={columns} 
              pagination={false} 
              bordered 
              rowKey="key"
              scroll={{ y: 300 }}
            />
            
            <Divider />
            
            <h3>总计</h3>
            <Table 
              dataSource={getFilteredResults('总计')} 
              columns={columns} 
              pagination={false} 
              bordered 
              rowKey="key"
              scroll={{ y: 150 }}
            />
          </div>
        </div>
      </div>
      </Modal>
    );
};

export default InvertedTriangularLoadCalculation;